package com.fts.fts.fitness_tracking_system.service.impl;

import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fts.fts.fitness_tracking_system.mapper.UsersMapper;
import com.fts.fts.fitness_tracking_system.pojo.Users;
import com.fts.fts.fitness_tracking_system.service.UsersService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author huawei
 * @description 针对表【users】的数据库操作Service实现
 * @createDate 2025-02-05 11:26:21
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {

    @Resource
    private UsersMapper usersMapper;

    @Override
    public Users userLogin(String username, String password) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<Users>()
                .and(qw -> qw.eq("username", username).or().eq("email", username))
                .eq("password", MD5.create().digestHex(password));

        return usersMapper.selectOne(queryWrapper);
    }

    @Override
    public void userRegister(Users user) {
        usersMapper.insert(user);
    }

    @Override
    public Users checkUser(String username) {
        return usersMapper.selectOne(new QueryWrapper<Users>().eq("username", username));
    }

    @Override
    public void updateUser(Users user) {
        usersMapper.updateById(user);
    }

    @Override
    public Users getUserInfo(Integer userId) {
        return usersMapper.selectById(userId);
    }

    @Override
    public Users getUserInfoByEmail(String email) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<Users>()
                .eq("email", email);
        return usersMapper.selectOne(queryWrapper);
    }

    @Override
    public void updatePassword(Integer userId,String newPassword) {
        Users user = usersMapper.selectById(userId);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        // 对新密码进行MD5加密
        String newPasswordMd5 = MD5.create().digestHex(newPassword);
        // 比较加密后的新密码与数据库中的旧密码
        boolean isSame = newPasswordMd5.equals(user.getPassword());
        if (isSame) {
            throw new IllegalArgumentException("新密码不能与旧密码相同");
        }
        // 更新密码
        user.setPassword(newPasswordMd5);
        usersMapper.updateById(user);
    }
}




